//
//  DoorSystemWiFiViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/3/13.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorSystemWiFiViewController.h"
#import "WWTableViewCell.h"
#import "WWAletView.h"
@interface DoorSystemWiFiViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>{
    
   
    SWifiAp wifiSSIDList[28];
    int wifiSSIDListCount;
    Boolean isRecvWiFi;
    Boolean isChangeWiFi;

}




/** tableview **/
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIButton *cleanbtn;
@property(nonatomic,strong) NSArray *titleArray;
/** Wi-Fi账号 **/
@property(nonatomic,strong) NSString *wifiSSID;

/** 弹出窗 **/
@property(nonatomic,strong) WWAletView *aletView;

/** camera **/
@property(nonatomic,strong)  MyCamera *camera;;
@end

@implementation DoorSystemWiFiViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [AppDelegate globalDelegate].cameraModel.delegate2 = self;

    // get WiFi info
    SMsgAVIoctrlListWifiApReq *structWiFi = malloc(sizeof(SMsgAVIoctrlListWifiApReq));
    memset(structWiFi, 0, sizeof(SMsgAVIoctrlListWifiApReq));
    
    [self.camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_LISTWIFIAP_REQ
                           Data:(char *)structWiFi
                       DataSize:sizeof(SMsgAVIoctrlListWifiApReq)];
    free(structWiFi);

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationStyle];
    [self masLayoutSubview];
    self.camera = [AppDelegate globalDelegate].cameraModel;
    self.titleArray = @[@"已连接Wi-Fi名称",@"WiFi密码"];
    
//    self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:<#(nonnull NSString *)#>
    
    
    self.camera = [AppDelegate globalDelegate].cameraModel;
    self.camera.delegate2 = self;
    // send list wifi request
    SMsgAVIoctrlListWifiApReq *structListWiFi = malloc(sizeof(SMsgAVIoctrlListWifiApReq));
    memset(structListWiFi, 0, sizeof(SMsgAVIoctrlListWifiApReq));
    
    [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_LISTWIFIAP_REQ Data:(char *)structListWiFi DataSize:sizeof(SMsgAVIoctrlListWifiApReq)];
    free(structListWiFi);
    
    
    wifiSSIDListCount = -1;
    memset(wifiSSIDList, 0, sizeof(wifiSSIDList));
    isRecvWiFi = false;
    isChangeWiFi = false;
    
    // send get wifi request
    SMsgAVIoctrlGetWifiReq *structGetWiFi = malloc(sizeof(SMsgAVIoctrlGetWifiReq));
    memset(structGetWiFi, 0, sizeof(SMsgAVIoctrlGetWifiReq));
    
    [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETWIFI_REQ Data:(char *)structGetWiFi DataSize:sizeof(SMsgAVIoctrlGetWifiReq)];
    free(structGetWiFi);
    
    
    __weak typeof (self.aletView)weakTanChuang = self.aletView;
    __weak typeof(self) weakself = self;

    self.aletView.pressSureBtn = ^(NSString *ssid,NSString *password,char mode,
                                   char enctype){
        
        
        
        NSLog(@"%c,%c",mode,enctype);
        SMsgAVIoctrlSetWifiReq *s = malloc(sizeof(SMsgAVIoctrlSetWifiReq));
        memcpy(s->ssid, [ssid UTF8String], 32);
        memcpy(s->password, [password UTF8String], 32);
        s->enctype = (int)encrypt;
        s->mode = (int)modf;
        
        [weakself.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SETWIFI_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlSetWifiReq)];
        
        free(s);

        
        weakself.aletView.hidden = YES;
        
        [SVProgressHUD showWithStatus:@"设置中,设备即将重启，请稍等..."];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [weakself.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"backVC" object:nil];

            
        });
        

    };

    self.aletView.pressCancelBtn = ^(){
       
        weakself.aletView.hidden = YES;
    };


}
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [AppDelegate globalDelegate].cameraModel.delegate2 = nil;
    
}
- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"WiFi设置" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
}
#pragma mark - tableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.titleArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 54.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}

#pragma mark - tableView Delegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WWTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WWTableViewCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    cell.tipLabel.text = self.titleArray[indexPath.row];
    
    if (isRecvWiFi == true) {
    
        if (indexPath.row == 0) {
            
            if ([self.wifiSSID length]>0) {
                cell.contentLabel.text = self.wifiSSID;

            }else{
                cell.contentLabel.text = @"无";

            }
            
            
        }else if (indexPath.row == 1){
            
            cell.contentLabel.text = @"********";
        }

        self.cleanbtn.enabled = YES;
        [self.cleanbtn setTitle:@"设备连接WiFi修改" forState:UIControlStateNormal];

    }else{
        if ([self.wifiSSID length]>0) {
            
            self.cleanbtn.enabled = YES;
            [self.cleanbtn setTitle:@"设备连接WiFi修改" forState:UIControlStateNormal];
            
        }else{
            
            self.cleanbtn.enabled = NO;
            [self.cleanbtn setTitle:@"获取Wi-Fi列表中..." forState:UIControlStateNormal];
        }
        if (indexPath.row == 0) {
            
            cell.contentLabel.text = self.wifiSSID;
            
            
        }else if (indexPath.row == 1){
            
            cell.contentLabel.text = @"********";
        }

    }
    
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}

#pragma mark - CameraDelegate Methods

- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    
    
    
    if (type == IOTYPE_USER_IPCAM_LISTWIFIAP_RESP) {
        
        SMsgAVIoctrlListWifiApResp *s = (SMsgAVIoctrlListWifiApResp *)data;
        //            wifiStatus = 0;
        
        for (int i = 0; i < s->number; ++i) {
            
            SWifiAp ap = s->stWifiAp[i];
            
            if (ap.status == 1 || ap.status == 2 || ap.status == 3 || ap.status == 4) {
                    
            self.wifiSSID = [[NSString alloc] initWithCString:ap.ssid encoding:NSUTF8StringEncoding];
                NSLog(@"WIFI--------%@",self.wifiSSID);
                [self.tableView reloadData];

            }
            
        }

    }
    
    if (type == IOTYPE_USER_IPCAM_LISTWIFIAP_RESP) {
        
        if (!isRecvWiFi) {
            memset(wifiSSIDList, 0, sizeof(wifiSSIDList));
            
            SMsgAVIoctrlListWifiApResp *p = (SMsgAVIoctrlListWifiApResp *)data;
            
            wifiSSIDListCount = p->number;
            memcpy(wifiSSIDList, p->stWifiAp, size - sizeof(p->number));
            
            [self.aletView reloadTableView:p typeSize:size listcount:wifiSSIDListCount];
            [self.tableView reloadData];
            isRecvWiFi = true;
        }
    }
    if (camera_ == self.camera && type == IOTYPE_USER_IPCAM_SETWIFI_RESP) {
        
        int result = -1;
        
        SMsgAVIoctrlSetWifiResp *s = (SMsgAVIoctrlSetWifiResp *)data;
        result = s->result;
        
        if (result == 0) {
            [SVProgressHUD showInfoWithStatus:@"修改Wi-Fi成功，设备即将重启，请等待..."];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [self.navigationController popViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"backrootview" object:nil];
            });
           

        }
        else {
            
            [SVProgressHUD showErrorWithStatus:@"密码错误"];
        }
    }

    
}


- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(superView);
        
    }];
    [self.cleanbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.centerY.mas_equalTo(superView.mas_centerY).mas_offset(-80);
        
    }];
}

- (void)cleanEvent{
    
    self.aletView.passwordfile.text = nil;
    self.aletView.hidden = NO;
    
    SWifiAp wifiAp = wifiSSIDList[0];
    NSString *ssid = [NSString stringWithUTF8String: wifiAp.ssid];
    self.aletView.selectwifilabel.text = ssid;
    
    
}
- (UIButton *)cleanbtn{
    
    if (!_cleanbtn) {
        __weak UIView *superView = self.view;
        
        _cleanbtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [superView addSubview:_cleanbtn];
        
        [_cleanbtn setBackgroundImage:[UIImage imageNamed:@"login_button_nor"] forState:UIControlStateNormal];
        [_cleanbtn setBackgroundImage:[UIImage imageNamed:@"login_button_sel"] forState:UIControlStateHighlighted];
        [_cleanbtn addTarget:self action:@selector(cleanEvent) forControlEvents:UIControlEventTouchUpInside];
        [_cleanbtn setTitle:@"设备连接WiFi修改" forState:UIControlStateNormal];
    }
    return _cleanbtn;
}


- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"WWTableViewCell" bundle:nil] forCellReuseIdentifier:@"WWTableViewCell"];
    }
    
    return _tableView;
    
}
- (WWAletView *)aletView{
    
    if (!_aletView) {
        
        __weak UIView *superView = self.view;
        _aletView = [[WWAletView alloc] initWithFrame:self.view.bounds];
        _aletView.titleLabel.text = @"设备连接WiFi修改";
        _aletView.hidden = YES;
        [superView addSubview:_aletView];
    }
    return _aletView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
